﻿using AutoMapper;
using MediatR;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.Repistory;
using U.B.WriteApi.Command;

namespace U.B.WriteApi.CommandHander
{
    public class UpdateurCommandHander : IRequestHandler<UpdateuserroleCommand, ApiResult<object>>
    {
        public readonly IRepistory<User> _userRepository;
        public readonly IMapper _mapper;
        public UpdateurCommandHander(IRepistory<User> userRepository, IMapper mapper)
        {
            _userRepository = userRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 用户修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<object>> Handle(UpdateuserroleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result = new ApiResult<object>();
            var list = _userRepository.GetAll().Where(x => x.UserName == request.UserName).Count();
            if (list < 0)
            {
                result.code = Renum.名字不得重复;
                result.Message = Renum.名字不得重复.ToString();

            }
            else
            {
                var user = _mapper.Map<User>(request);
                var now = DateTime.Now;
                user.Updateor = "刀哥";
                user.Updatedate = now;

                var u = _userRepository.UpdateAsync(user).Result;
                result.code = Renum.修改成功;
                result.Message = Renum.修改成功.ToString();
                result.Data = u;
            }
            return await Task.FromResult(result);
        }
    }
}
